#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
using namespace std;

void daemonize(){
	int fd;
	pid_t pid;

	if((pid=fork())<0){
		cout<<"can't create subprocess!"<<endl;
	}
  	else{//subprocess have been created
		if(pid!=0){
			exit(0);//exit parent process
		}
	}
	
	setsid();

	if(chdir("/")<0){ //	切换工作目录到根目录失败
		cout<<"can't change dir!"<<endl;
		exit(-1);
	}

	fd=open("/dev/null",O_RDWR);
	dup2(fd,STDIN_FILENO);//redirect input
	dup2(fd,STDOUT_FILENO);//redirect output
	dup2(fd,STDERR_FILENO);//redirect error

	return;
}

int main(){
	daemonize();//switch process to background
	while(1){
		sleep(1);
	}
}
